﻿if exists (select * from sysobjects where name like N'%sp_DMHangHoa_InsertUpdate%')
	drop proc sp_DMHangHoa_InsertUpdate
go
create proc sp_DMHangHoa_InsertUpdate
	@MaHangHoa varchar(20),
	@TenHangHoa nvarchar(255) = null,
	@MaDonViTinh int = null,
	@DonGia decimal(5,2) = null,
	@IsUse bit = null,
	@IsDelete bit = null,
	@CreateBy int = null,
	@ModifiedBy int = null,
	@ModifiedOn datetime = null,
	@XML ntext = null
as
begin
	declare @iDoc int
	exec sp_xml_preparedocument @iDoc output, @XML
	select @MaHangHoa = MaHangHoa, @TenHangHoa = TenHangHoa, @MaDonViTinh = MaDonViTinh,
		@DonGia = DonGia, @IsUse = IsUse, @IsDelete = IsDelete, @CreateBy = CreateBy,
		@ModifiedBy = ModifiedBy, @ModifiedOn = ModifiedOn
	from openxml(@iDoc, N'/Root/DMHangHoa')
	with (MaHangHoa varchar(20), TenHangHoa nvarchar(255), MaDonViTinh int, DonGia decimal(5,2),
		IsUse bit, IsDelete bit, CreateBy int, ModifiedBy int, ModifiedOn datetime)

	exec sp_xml_removedocument @iDoc

	if not exists (select * from DMHangHoa where MaHangHoa = @MaHangHoa)
	begin
		insert into DMHangHoa(MaHangHoa, TenHangHoa, MaDonViTinh, DonGia, IsUse, IsDelete, CreateBy)
		values (@MaHangHoa, @TenHangHoa, @MaDonViTinh, @DonGia, @IsUse, @IsDelete, @CreateBy)
	end

	else
	begin
		update DMHangHoa
		set TenHangHoa = @TenHangHoa, 
			MaDonViTinh = @MaDonViTinh,
			DonGia = @DonGia,
			IsUse = @IsUse,
			ModifiedBy = @ModifiedBy,
			ModifiedOn = @ModifiedOn
		where MaHangHoa = @MaHangHoa
	end
end